package com.example.drcbackend.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Service
@Transactional
public class SubsetService {

    public boolean CheckSubset(int DBid, int setdbid) {
        try {
            // 读取两个SQL文件的内容
            String dbFilePath = "E:/SQL_test/" + DBid + ".sql";
            List<String> dbLines = Files.readAllLines(Paths.get(dbFilePath), StandardCharsets.UTF_8);
            String subFilePath = "E:/SQL_test/" + setdbid + ".sql";
            List<String> subLines = Files.readAllLines(Paths.get(subFilePath), StandardCharsets.UTF_8);

            // 解析元组数据
            Map<String, Set<String>> dbTuples = parseInsertTuples(dbLines);
            Map<String, Set<String>> subTuples = parseInsertTuples(subLines);

            // 检查子集关系
            for (Map.Entry<String, Set<String>> entry : subTuples.entrySet()) {
                String table = entry.getKey();
                Set<String> subSet = entry.getValue();
                Set<String> dbSet = dbTuples.get(table);

                if (dbSet == null || !dbSet.containsAll(subSet)) {
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private Map<String, Set<String>> parseInsertTuples(List<String> lines) {
        Map<String, Set<String>> tuplesMap = new HashMap<>();
        Pattern insertPattern = Pattern.compile(
                "^INSERT INTO\\s+`?(\\w+)`?\\s*(?:.*?\\s*)?VALUES\\s+(.+);?$",
                Pattern.CASE_INSENSITIVE
        );

        for (String line : lines) {
            line = line.trim();
            if (line.toUpperCase().startsWith("INSERT INTO")) {
                Matcher matcher = insertPattern.matcher(line);
                if (matcher.find()) {
                    String table = matcher.group(1);
                    String valuesPart = matcher.group(2).replaceAll(";\\s*$", "").trim();

                    // 提取所有元组
                    Pattern tuplePattern = Pattern.compile("\\(([^)]+)\\)");
                    Matcher tupleMatcher = tuplePattern.matcher(valuesPart);
                    while (tupleMatcher.find()) {
                        String tupleContent = tupleMatcher.group(1);
                        // 标准化处理：去除多余空格
                        String normalized = "(" + tupleContent.replaceAll("\\s+", " ").trim().replaceAll(", ", ",") + ")";
                        tuplesMap.computeIfAbsent(table, k -> new HashSet<>()).add(normalized);
                    }
                }
            }
        }
        return tuplesMap;
    }
}
